package com.yx.cloud.activity;

import android.content.Intent;
import android.os.Build;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Toast;

import com.google.gson.Gson;
import com.iot.base.bean.account.Account;
import com.iot.base.service.req.ConfigRecordSaveParam;
import com.iot.common.utils.Event;
import com.iot.common.utils.LogUtils;
import com.iot.sdk.yugong.resp.YuGongRespCreateDevice;
import com.iot.sdk.yugong.resp.YuGongRespDataGetUserInfo;
import com.iot.sweeper.AppContext;
import com.yx.cloud.R;
import com.yx.cloud.base.BaseActivity;
import com.yx.cloud.bean.CreateDeviceParam;
import com.yx.cloud.constant.Constants;
import com.yx.cloud.databinding.SelectwifiActivityBinding;
import com.yx.cloud.product.laser.tuyapublic.BluetoothScanDeviceBean;
import com.yx.cloud.utils.Intent_utils;
import com.yx.cloud.utils.LoadProgressDialog;
import com.yx.cloud.utils.LocationUtils;
import com.yx.cloud.utils.RomUtils;
import com.yx.cloud.utils.SharedPrefsUtil;
import com.yx.cloud.utils.ToastUtil;
import com.yx.cloud.utils.WifiManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * WIFI帐号选择界面 2017/8/18.
 */

public class SelectWIFIActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "SelectWIFIActivity";
    public int REQUEST_CODE_ASK_PERMISSIONS = 1;
    private WifiManager xw;
    private SelectwifiActivityBinding binding;
    private String network, source;
    private BluetoothScanDeviceBean bluetoothData;
    private LoadProgressDialog loadProgressDialog;
    private String device_type;

    @Override
    public void onCreate() {
        binding = SelectwifiActivityBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {//加上判断
            EventBus.getDefault().register(this);
        }
        initData();
    }

    private void initData() {
        Log.d(TAG, "--------------------------------initData");
        loadProgressDialog = new LoadProgressDialog(this);
        xw = new WifiManager(SelectWIFIActivity.this);

        network = getIntent().getStringExtra("network");
        if (!"qrcode".equals(network)) {
            //预留二维码配网
        }
        if ("bluetooth".equals(network)) {
            bluetoothData = (BluetoothScanDeviceBean) getIntent().getSerializableExtra("bluetoothData");
            source = getIntent().getStringExtra("source");
        } else {
//            if (ZW2X.get().getConfig().productName.equals(AppContext.get().getRobotType())) {
//                binding.tvNetworkTips.setText(getString(R.string.Support_3));
//            }
        }
        device_type = getIntent().getStringExtra("device_type");
        String mWifiName = SharedPrefsUtil.getValue(this, "wifi_account", "mWifiName", "");
        String mWifiPassWord = SharedPrefsUtil.getValue(this, "wifi_passWord", "mWifiPassWord", "");
        String ssid = xw.getConnectedSSID();
        String mSsid = whetherToRemoveTheDoubleQuotationMarks(ssid);
        Log.d(TAG, "-------------------------------- ssid : " + mSsid);
        if (!TextUtils.isEmpty(mSsid)) {
            binding.selectwifiEtAccount.setText(mSsid);
            if (mWifiName.equals(mSsid) && !TextUtils.isEmpty(mWifiPassWord)) {
                binding.selectwifiEtPassword.setText(mWifiPassWord);
            } else {
                binding.selectwifiEtPassword.setText("");
            }
        }
        if (binding.selectwifiEtAccount.length() > 0) {
            binding.selectWIFIBtnNext.setEnabled(true);
            Log.d(TAG, "--------------------------------");
        } else {
            binding.selectWIFIBtnNext.setEnabled(false);
        }

        binding.selectwifiEtPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());//默认隐藏密码
        binding.ivSelectEye.setChecked(false);

        binding.selectwifiEtAccount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.length() > 0) {
                    binding.selectWIFIBtnNext.setEnabled(true);
                } else {
                    binding.selectWIFIBtnNext.setEnabled(false);
                }
                //设置光标位置
                binding.selectwifiEtAccount.setSelection(binding.selectwifiEtAccount.length());
            }
        });

        binding.ivSelectwifiReturn.setOnClickListener(this);
        binding.selectwifiTvPopwind.setOnClickListener(this);
        binding.selectWIFIBtnNext.setOnClickListener(this);
        binding.ivSelectEye.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (RomUtils.isFastClick()) {
            return;
        }
        switch (v.getId()) {
            case R.id.iv_selectwifi_return:
                Intent_utils.backIntent(this);
                break;
            case R.id.iv_selectEye:
                //选择隐藏显示密码
                if (binding.ivSelectEye.isChecked()) {
                    //显示
                    Log.d(TAG, "visible is checked " + binding.ivSelectEye.isChecked());
                    binding.selectwifiEtPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    //隐藏
                    Log.d(TAG, "invisible is checked " + binding.ivSelectEye.isChecked());
                    binding.selectwifiEtPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
                binding.selectwifiEtPassword.setSelection(binding.selectwifiEtPassword.getText().toString().trim().length());
                break;
            case R.id.selectwifi_tv_popwind:
                //WIFI列表
                Intent intent = new Intent();
                intent.setAction("android.net.wifi.PICK_WIFI_NETWORK");
                startActivityForResult(intent, 123);
                break;
            case R.id.selectWIFI_btn_next:
                //需要发送给机器的wifi帐号密码
                String mWifiName = binding.selectwifiEtAccount.getText().toString();
                String mWifiPassWord = binding.selectwifiEtPassword.getText().toString();

                SharedPrefsUtil.putValue(this, "wifi_account", "mWifiName", mWifiName);
                SharedPrefsUtil.putValue(this, "wifi_passWord", "mWifiPassWord", mWifiPassWord);
                Constants.wifi_Name = mWifiName;
                Constants.wifi_Pass = mWifiPassWord;
                loadProgressDialog.show();
                Account account = AppContext.get().getAccount();
                LogUtils.i(device_type + "--------------------------------account  " + new Gson().toJson(account));
                if (account == null) {
                    AppContext.getAccountService().getUserInfo();
                } else {
                    String userAccount = account.getAccount();
                    if (userAccount.equals("")) {
                        AppContext.getAccountService().getUserInfo();
                    } else {
                        AppContext.getAccountService().createDevice(device_type);
                    }
                }
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(Event event) {
        switch (event.getType()) {
            case Event.MESSAGE_TYPE_CREATE_DEVICE:
                if (loadProgressDialog != null) {
                    loadProgressDialog.dismiss();
                }
                //创建设备返回数据
                if (event.isResult()) {
                    String userAccount = AppContext.get().getAccount().getAccount();
                    YuGongRespCreateDevice data = (YuGongRespCreateDevice) event.getContent();
//                    LogUtils.i("data : " + new Gson().toJson(data));
                    String cacert = data.getCacert();
                    String cert = data.getCert();
                    String private_key = data.getPrivate_key();
                    String endpoint = data.getEndpoint();
                    String region_name = data.getRegion_name();
//                    String device_type = data.getDevice_type();
                    String thing_name = data.getThing_name();
                    Integer timestamp_s = data.getTimestamp_s();
                    LogUtils.i("--------------------------------cacert " + cacert);
                    LogUtils.i("--------------------------------cert " + cert);
                    LogUtils.i("--------------------------------private_key " + private_key);
                    LogUtils.i("--------------------------------endpoint " + endpoint);
                    LogUtils.i("--------------------------------region_name " + region_name);
                    LogUtils.i("--------------------------------thing_name " + thing_name);
                    LogUtils.i("--------------------------------timestamp_s " + timestamp_s);
                    LogUtils.i("--------------------------------device_type w " + device_type);
                    LogUtils.i("--------------------------------device_type " + device_type);
                    if (TextUtils.isEmpty(cacert) || TextUtils.isEmpty(cert) || TextUtils.isEmpty(private_key)
                            || TextUtils.isEmpty(endpoint) || TextUtils.isEmpty(region_name)
                            || TextUtils.isEmpty(thing_name) || TextUtils.isEmpty(userAccount)
                            || TextUtils.isEmpty(device_type)) {
                        ToastUtil.show(this, "Some parameters are empty", Toast.LENGTH_SHORT);
                        return;
                    }
                    CreateDeviceParam param = new CreateDeviceParam();
                    param.setWifi_name(Constants.wifi_Name);
                    param.setWifi_password(Constants.wifi_Pass);
                    param.setCacert(cacert);
                    param.setCert(cert);
                    param.setPrivate_key(private_key);
                    param.setEndpoint(endpoint);
                    param.setRegion_info(region_name);
                    param.setUser_account(userAccount);
                    param.setDevice_type(device_type);
                    param.setApp_info("SilverStar");
                    param.setThingname(thing_name);
                    param.setTimestamp_s(timestamp_s);

                    if ("bluetooth".equals(network)) {
                        //蓝牙 方式配网
                        if ("X5".equals(source)) {
                            //X5蓝牙 方式配网 天猫
                            Intent intent_bluetooth_x5 = new Intent(SelectWIFIActivity.this, DeviceBluetoothConnectActivity.class);
                            intent_bluetooth_x5.putExtra("network", "bluetooth");
                            intent_bluetooth_x5.putExtra("bluetoothData", bluetoothData);
                            intent_bluetooth_x5.putExtra("config_bean", param);
                            intent_bluetooth_x5.putExtra("device_type", device_type);
                            startActivity(intent_bluetooth_x5);
                            finish();
                        } else {
                            //其他机型蓝牙 方式配网
                            Intent intent_bluetooth = new Intent(SelectWIFIActivity.this, DeviceConnectActivity2.class);
                            intent_bluetooth.putExtra("network", "bluetooth");
                            intent_bluetooth.putExtra("bluetoothData", bluetoothData);
                            intent_bluetooth.putExtra("config_bean", param);
                            intent_bluetooth.putExtra("device_type", device_type);
                            startActivity(intent_bluetooth);
                            finish();
                        }
                    } else if ("qrcode".equals(network)) {
                        //二维码配网
                        Intent intent_qrcode = new Intent(SelectWIFIActivity.this, QrCodeAddEquipmentActivity.class);
                        intent_qrcode.putExtra("network", "qrcode");
                        intent_qrcode.putExtra("device_type", device_type);
                        startActivity(intent_qrcode);
                        finish();
                    } else {
                        //wifi 方式配网
                        String ezAndAP = SharedPrefsUtil.getValue(this, "EZandAP", "EZandAP", "");
                        if (ezAndAP.equals("EZ")) {
                            Intent intent_ez = new Intent(SelectWIFIActivity.this, DeviceConnectActivity2.class);
                            intent_ez.putExtra("network", "wifi");
                            intent_ez.putExtra("device_type", device_type);
                            startActivity(intent_ez);
                            finish();
                        } else {
                            //AP
                            Intent intent = new Intent(SelectWIFIActivity.this, ConnectSketchMapActivity.class);
                            intent.putExtra("network", "wifi");
                            intent.putExtra("config_bean", param);
                            intent.putExtra("device_type", device_type);
                            startActivity(intent);
                            finish();
                        }
                    }
                } else {
                    ToastUtil.show(this, "Failed to create a device : " + event.getContent().toString(), Toast.LENGTH_SHORT);
                    LogUtils.i("--------------------------------获取信息失败 " + event.getContent().toString());
                }
                break;
            case Event.MESSAGE_TYPE_GET_ACCOUNT_INFO:
                // 用户信息
                if (event.isResult()) {
                    Account account = (Account) event.getContent();
                    LogUtils.i("用户信息 : " + new Gson().toJson(account));
                    AppContext.get().setAccount(account);
                    AppContext.getAccountService().createDevice(device_type);
                } else {
                    if (loadProgressDialog != null) {
                        loadProgressDialog.dismiss();
                    }
                    ToastUtil.show(this, event.getContent().toString(), Toast.LENGTH_SHORT);
                }
                break;
        }
    }


    //根据Android的版本判断获取到的SSID是否有双引号
    public String whetherToRemoveTheDoubleQuotationMarks(String ssid) {
        //获取Android版本号
        int deviceVersion = Build.VERSION.SDK_INT;
        if (deviceVersion >= 17) {
            if (ssid.startsWith("\"") && ssid.endsWith("\"")) {
                ssid = ssid.substring(1, ssid.length() - 1);
            }
        }
        return ssid;
    }

    @Override
    protected void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Constants.isBack = false;
        }
        return super.onKeyDown(keyCode, event);
    }

}
